package com.example.schedulemanager.view;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.schedulemanager.R;
import com.example.schedulemanager.model.Schedule;
import com.example.schedulemanager.utils.AlarmScheduler;
import com.example.schedulemanager.viewmodel.ScheduleViewModel;
import com.google.android.material.textfield.TextInputLayout;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class EditScheduleActivity extends AppCompatActivity {
    
    private EditText titleEditText, descriptionEditText, dateEditText, timeEditText;
    private TextInputLayout titleLayout, descriptionLayout, dateLayout, timeLayout;
    private Button saveButton, cancelButton;
    private ScheduleViewModel scheduleViewModel;
    private Calendar calendar;
    private Schedule currentSchedule;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_schedule);
        
        // 初始化视图
        titleEditText = findViewById(R.id.titleEditText);
        descriptionEditText = findViewById(R.id.descriptionEditText);
        dateEditText = findViewById(R.id.dateEditText);
        timeEditText = findViewById(R.id.timeEditText);
        
        titleLayout = findViewById(R.id.titleLayout);
        descriptionLayout = findViewById(R.id.descriptionLayout);
        dateLayout = findViewById(R.id.dateLayout);
        timeLayout = findViewById(R.id.timeLayout);
        
        saveButton = findViewById(R.id.saveButton);
        cancelButton = findViewById(R.id.cancelButton);
        
        // 初始化ViewModel
        scheduleViewModel = new ViewModelProvider(this).get(ScheduleViewModel.class);
        
        // 初始化日历
        calendar = Calendar.getInstance();
        
        // 获取日程ID
        int scheduleId = getIntent().getIntExtra("schedule_id", -1);
        if (scheduleId != -1) {
            scheduleViewModel.getScheduleById(scheduleId, schedule -> {
                if (schedule != null) {
                    currentSchedule = schedule;
                    titleEditText.setText(currentSchedule.getTitle());
                    descriptionEditText.setText(currentSchedule.getDescription());
                    dateEditText.setText(currentSchedule.getDate());
                    timeEditText.setText(currentSchedule.getTime());
                }
            });
        }
        
        // 设置日期选择器
        dateEditText.setOnClickListener(v -> showDatePicker());
        
        // 设置时间选择器
        timeEditText.setOnClickListener(v -> showTimePicker());
        
        // 设置保存按钮
        saveButton.setOnClickListener(v -> updateSchedule());
        
        // 设置取消按钮
        cancelButton.setOnClickListener(v -> finish());
    }
    
    private void showDatePicker() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    String date = String.format(Locale.getDefault(), "%04d-%02d-%02d", year, month + 1, dayOfMonth);
                    dateEditText.setText(date);
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        
        // 设置最小日期为今天
        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }
    
    private void showTimePicker() {
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, hourOfDay, minute) -> {
                    String time = String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
                    timeEditText.setText(time);
                },
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
        );
        timePickerDialog.show();
    }
    
    private void updateSchedule() {
        if (currentSchedule == null) {
            Toast.makeText(this, "日程不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        
        String title = titleEditText.getText().toString().trim();
        String description = descriptionEditText.getText().toString().trim();
        String date = dateEditText.getText().toString().trim();
        String time = timeEditText.getText().toString().trim();
        
        // 验证输入
        if (TextUtils.isEmpty(title)) {
            titleLayout.setError("请输入日程标题");
            return;
        }
        
        if (TextUtils.isEmpty(date)) {
            dateLayout.setError("请选择日期");
            return;
        }
        
        if (TextUtils.isEmpty(time)) {
            timeLayout.setError("请选择时间");
            return;
        }
        
        // 验证日期不能是过去的时间
        if (!isValidDate(date, time)) {
            Toast.makeText(this, "不能设置过去时间的日程", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 取消旧的闹钟
        AlarmScheduler.cancelAlarm(getApplicationContext(), currentSchedule);

        // 更新日程
        currentSchedule.setTitle(title);
        currentSchedule.setDescription(description);
        currentSchedule.setDate(date);
        currentSchedule.setTime(time);
        
        // 设置提醒时间
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
            Date scheduleDate = sdf.parse(date + " " + time);
            if (scheduleDate != null) {
                currentSchedule.setReminderTime(scheduleDate.getTime());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // 保存到数据库
        scheduleViewModel.update(currentSchedule);
        
        // 设置新的闹钟
        AlarmScheduler.scheduleAlarm(getApplicationContext(), currentSchedule);

        Toast.makeText(this, "日程已更新", Toast.LENGTH_SHORT).show();
        finish();
    }
    
    private boolean isValidDate(String date, String time) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
            Date scheduleDate = sdf.parse(date + " " + time);
            Date currentDate = new Date();
            
            return scheduleDate != null && scheduleDate.after(currentDate);
        } catch (Exception e) {
            return false;
        }
    }
} 